<template>
    <div class="user-profile">
      <h2>查看/修改个人信息</h2>
      <el-form :model="userInfo" label-width="100px" style="max-width: 600px;">
        <el-form-item label="用户名">
          <el-input v-model="userInfo.username" disabled></el-input>
        </el-form-item>
        <el-form-item label="角色">
          <el-input v-model="userInfo.role" disabled></el-input>
        </el-form-item>
        <el-form-item label="新密码">
          <el-input type="password" v-model="newPassword" placeholder="留空表示不修改密码" show-password></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="updateUserAccount">更新信息</el-button>
        </el-form-item>
      </el-form>
    </div>
  </template>
  
  <script setup>
  import { ref, reactive, onMounted } from 'vue'
  import { useUserStore } from '../../stores/user'
  import { ElMessage } from 'element-plus'
  
  const userStore = useUserStore()
  const userInfo = reactive({
    username: '',
    role: ''
  })
  const newPassword = ref('')
  
  onMounted(() => {
    userInfo.username = userStore.username
    userInfo.role = userStore.role === 'ADMIN' ? '管理员' : '用户'
  })
  
  const updateUserAccount = async () => {
    if (!newPassword.value) {
      ElMessage.info('未输入新密码，将不修改密码。')
      return
    }
    if (newPassword.value.length < 6) {
      ElMessage.error('新密码至少需要6位！')
      return
    }
  
    try {
      const res = await userStore.updatePassword(userStore.username, newPassword.value)
      if (res.success) {
        ElMessage.success(res.message)
        newPassword.value = ''
      } else {
        ElMessage.error(res.message || '更新失败！')
      }
    } catch (error) {
      console.error('更新个人信息失败:', error)
      ElMessage.error(error.message || '更新失败，请稍后重试。')
    }
  }
  </script>
  
  <style scoped>
  .user-profile {
    padding: 20px;
  }
  </style>